var PeopleMedia = PeopleMedia || {};

PeopleMedia.FacebookInterests = {
        Actions: {}, // any ajax urls are saved in here
	    AppID: '267404250001521', // rewritten by the init
        DefaultSearchString: '',
		StartTime: null,
		EndTime: null,
		FacebookInitRan: false,
        FacebookImportRan: false,
		DetailCount: 0,
		FQLString: 'SELECT name, about, pic_small, page_id, type , is_verified , genre , fan_count'
				+ ' FROM page '
				+ ' WHERE page_id IN (SELECT page_id '
				+ ' FROM page_fan '
				+ ' WHERE uid = me() ) '
				+ '    AND (type = "Musician/Band"  '
				+ '      OR type = "Movie" '
				+ '      OR type = "TV Show" '
				+ '      OR type = "album" '
				+ '      OR type = "Travel/Leisure" '
				+ '      OR type = "Sports Venue" '
				+ '      OR type = "Attractions/Things to Do" '
				+ '      OR type = "Sports/Recreation/Activities" '
				+ '      OR type = "Professional Sports Team")'
				+ ' ORDER BY fan_count DESC',
		PageCount: 0,
		PageCountMax: 10,
	    UserLikes: new Array(),
	    UserMovies: new Array(),
  	    UserMusic: new Array(),
   	    UserActivities: new Array(),
   	    UserNoCategory: new Array(),
   	    UserLikesSorted: new Array(),
   	    UserLikesDeleted: new Array(),
   	    UserLikesAdded: new Array(),
   	    CurrentSearchTermLookup: "",
   	    PreviousSearchTermLookup: "",
	    SortLikes: function(like1,like2){
		    if (like1.name === like2.name) return 0;
		    if (like1.name > like2.name) return 1;
		    return -1;
	    },
	    PopularLikes: function(like1,like2)
	    {
			return like2.likes - like1.likes;
	    },
	    CallFacebookAPIForImport: function ()
	    {
	        if (!PeopleMedia.FacebookInterests.FacebookImportRan)
	        {
	            $jq("#fblikesimportcontainer").show();
	            PeopleMedia.FacebookInterests.FacebookImportRan = true;
	            FB.api({ method: 'fql.query', query: PeopleMedia.FacebookInterests.FQLString }, function (response) {
	                PeopleMedia.FacebookInterests.PageCount++;

	                if (response.error == undefined) {
	                    if (response.data != undefined) {
	                        var theData = response.data;
	                    }
	                    else {
	                        var theData = response;
	                    }

	                    PeopleMedia.FacebookInterests.UserLikes = PeopleMedia.FacebookInterests.UserLikes.concat(theData);
                        PeopleMedia.FacebookInterests.DisplayUserLikes();
	                }
	                else {
	                    PeopleMedia.FacebookInterests.Output("<b>There was an error!</b>");
	                    //PeopleMedia.FacebookInterests.OutputHelper(response);
	                }

	            });
	        }
    	},
	    FormatLikes: function (x) {
		    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		},
		LoadDisplayOfCategory: function(title,arrayData){
			
			$jq("#LikesDisplay").append("<h3>" + title + "<h3/>");
			
			for (var i=0; i<arrayData.length; i++)
			{
				$jq("#LikesDisplay").append($jq('<div class="LikeRow" data-likes="'+arrayData[i].likes+'" data-category="'+arrayData[i].category+'">'
						//+ '<div class="LikePicture">'
						//	+ arrayData[i].picture
						//+ '</div>'
						+ '<div class="LikeName">'
							+ arrayData[i].name
						+ '</div>'
						+ '<div class="LikeCategory">'
							+ ' '
							+ arrayData[i].category
							+ ' - '
							+ PeopleMedia.FacebookInterests.FormatLikes(arrayData[i].likes)
							+ ' like this'
						+ '</div>'
					+ '</div>')
				);
			}
		},
	    DisplayCategories: function(){
    	
	        var hasResults = false;

	        if (PeopleMedia.FacebookInterests.UserMovies.length > 0)
	        {
	            hasResults = true;
	            PeopleMedia.FacebookInterests.Output("Found " + PeopleMedia.FacebookInterests.UserMovies.length + " movie interests.");
	        }

	        if (PeopleMedia.FacebookInterests.UserMusic.length > 0) {
	            hasResults = true;
	            PeopleMedia.FacebookInterests.Output("Found " + PeopleMedia.FacebookInterests.UserMusic.length + " music interests.");
	        }

	        if (PeopleMedia.FacebookInterests.UserActivities.length > 0) {
	            hasResults = true;
	            PeopleMedia.FacebookInterests.Output("Found " + PeopleMedia.FacebookInterests.UserActivities.length + " activity interests.");
	        }

	        if (hasResults) {

	            var myArray = JSON.stringify({ 'userLikes': PeopleMedia.FacebookInterests.UserLikesSorted });

	            $jq.ajax({
	                contentType: 'application/json; charset=utf-8',
	                dataType: 'json',
	                type: "POST",
	                url: PeopleMedia.FacebookInterests.Actions.SaveImportedInterestsUrl,
	                traditional: true,
	                data: myArray,
	                success: function (response) {
	                    $jq("#fblikesimportcontainerwait").hide();
	                    $jq("#fblikesimportcontainercomplete").show();
	                    PeopleMedia.FacebookInterests.ShowAddSaveResults(response);
	                },
	                failure: function (response) {
	                    $jq("#fblikesimportcontainerwait").hide();
	                    $jq("#fblikesimportcontainercomplete").show();
	                }
	            });
	        } else {
	            PeopleMedia.FacebookInterests.Output("No interests were found.");
	            $jq("#fblikesimportcontainerwait").hide();
	            $jq("#fblikesimportcontainercomplete").show();
	        }
    
	    },
	    FilterShowAddSaveResults: function(){
	        var movies = $jq("#fblikesimportcontainercomplete_1").html();
	        var music = $jq("#fblikesimportcontainercomplete_2").html();
	        var activities = $jq("#fblikesimportcontainercomplete_3").html();
	        var hasResults = false;

	        if (movies.length > 40) {
	            hasResults = true;
	            $jq("#fblikes_movies_add").show();
	        } else {
	            $jq("#fblikes_movies_add").hide()
	        }

	        if (music.length > 40) {
	            hasResults = true;
	            $jq("#fblikes_music_add").show();
	        } else {
	            $jq("#fblikes_music_add").hide()
	        }

	        if (activities.length > 40) {
	            hasResults = true;
	            $jq("#fblikes_activities_add").show();
	        } else {
	            $jq("#fblikes_activities_add").hide()
	        }


	        if (!hasResults) {
	            $jq("#fblikes_none_add").show();
	        } else {
	            $jq("#fblikes_none_add").hide();
	        }

	    },
	    ShowAddSaveResults: function(response){
	        if (response.data != null) {
	            for (var i = 0; i < response.data.length; i++) {
	                $jq("#fblikesimportcontainercomplete_" + response.data[i].CategoryId).append($jq('<div class="fblikechoice" data-interestid="' + response.data[i].InterestId + '" data-interestname="' + response.data[i].InterestName + '" data-externalobjectid="' + response.data[i].ExternalObjectId + '" data-likes="' + response.data[i].TotalLikes + '" data-category="' + response.data[i].CategoryId + '">'
                            + response.data[i].InterestName
                            + '<span>&nbsp;&nbsp;&nbsp;</span>'
                        + '</div>')
                    );
	            }

	            PeopleMedia.FacebookInterests.FilterShowAddSaveResults();

	            $jq("#fblikesimportcontainercomplete .fblikechoice").hover(function () {
	                var mainBox = $jq(this);
	                $jq(this).addClass("fblikechoicehoveredit");
	                $jq(this).find("span").html($jq("#fbclosebuttoncontainer").html());
	                $jq(this).find("span img").click(function () {
	                    mainBox.fadeOut();
	                    PeopleMedia.FacebookInterests.DeleteInterest(mainBox.attr("data-interestid"));
	                    mainBox.remove();
	                    PeopleMedia.FacebookInterests.FilterShowAddSaveResults();
	                });
	            }, function () {
	                $jq(this).removeClass("fblikechoicehoveredit");
	                $jq(this).find("span").html("&nbsp;&nbsp;&nbsp;");
	                $jq(this).find("span img").click(function () {
	                });
	            });
	        }
	    },
	    DisplayUserLikes: function () {
			
			var maxResults = 2000;

		    if( PeopleMedia.FacebookInterests.UserLikes.length < maxResults) {
		      maxResults = PeopleMedia.FacebookInterests.UserLikes.length;
		    }   

			for( i=0; i<maxResults; i++) {

			  		//PeopleMedia.FacebookInterests.OutputHelper(response);
					PeopleMedia.FacebookInterests.DetailCount++;

					var dataArray = {};
					var saveData = {};

			  		// Create sorted Array using Likes and a few extra
			  		dataArray = new Array();
			  		dataArray.id = PeopleMedia.FacebookInterests.UserLikes[i].page_id;
			  		dataArray.name = "<a href='http://www.facebook.com/" + dataArray.id + "' target='_blank'>"
					  		+ PeopleMedia.FacebookInterests.UserLikes[i].name
					  		+ "</a>";
			  		dataArray.likes = PeopleMedia.FacebookInterests.UserLikes[i].fan_count;
			  		dataArray.type = PeopleMedia.FacebookInterests.UserLikes[i].type;
			  		dataArray.category = dataArray.type.toLowerCase();
			  		dataArray.picture = "<a href='http://www.facebook.com/" + dataArray.id + "' target='_blank'>"
			  		+ "<img src='"+PeopleMedia.FacebookInterests.UserLikes[i].pic_small+"' />"
			  		+ "</a>";

			        /* data we care about to save */
			  		saveData.Reviewed = false;
			  		saveData.InterestId = 0;
			  		saveData.ExternalObjectId = PeopleMedia.FacebookInterests.UserLikes[i].page_id;
			  		saveData.InterestName = PeopleMedia.FacebookInterests.UserLikes[i].name;
			  		saveData.TotalLikes = PeopleMedia.FacebookInterests.UserLikes[i].fan_count;
			  		saveData.CategoryId = PeopleMedia.FacebookInterests.UserLikes[i].type; // rewritten below

					if (dataArray.category.indexOf("movie") != -1 || dataArray.category.indexOf("tv show") != -1 ) {
					    saveData.CategoryId = "1";
					    PeopleMedia.FacebookInterests.UserMovies[PeopleMedia.FacebookInterests.UserMovies.length] = dataArray;
					} else if (dataArray.category.indexOf("music") != -1) {
					    saveData.CategoryId = "2";
						PeopleMedia.FacebookInterests.UserMusic[PeopleMedia.FacebookInterests.UserMusic.length] = dataArray;
					} else if (dataArray.category.indexOf("travel") != -1
						|| dataArray.category.indexOf("leisure") != -1
						|| dataArray.category.indexOf("sports") != -1
						|| dataArray.category.indexOf("sports team") != -1
						|| dataArray.category.indexOf("attractions") != -1
						|| dataArray.category.indexOf("things to do") != -1
						|| dataArray.category.indexOf("recreation") != -1
						|| dataArray.category.indexOf("activities") != -1
						|| dataArray.category.indexOf("sports venue") != -1
					) {
					    saveData.CategoryId = "3";
					    PeopleMedia.FacebookInterests.UserActivities[PeopleMedia.FacebookInterests.UserActivities.length] = dataArray;
					} else {
						PeopleMedia.FacebookInterests.UserNoCategory[PeopleMedia.FacebookInterests.UserNoCategory.length] = dataArray;					
					}

					PeopleMedia.FacebookInterests.UserLikesSorted[PeopleMedia.FacebookInterests.UserLikesSorted.length] = saveData;

			};
			
            // always attempt to display, this will now handle no results
			PeopleMedia.FacebookInterests.DisplayCategories();
					   
			
       	},
	    Init: function (siteSpecificAppID) {
	        PeopleMedia.FacebookInterests.AppID = siteSpecificAppID;
	        PeopleMedia.FacebookInterests.DefaultSearchString = $jq("#fblikessearchinput").attr('data-default');

	        $jq(".fblikechoiceareaselected .fblikechoice").hover(function () {
	            var mainBox = $jq(this);
	            $jq(this).addClass("fblikechoicehoveredit");
	            $jq(this).find("span").html($jq("#fbclosebuttoncontainer").html());
	            $jq(this).find("span img").click(function () {
	                mainBox.fadeOut();
	                PeopleMedia.FacebookInterests.DeleteInterest(mainBox.attr("data-interestid"));
	            });
	        }, function () {
	            $jq(this).removeClass("fblikechoicehoveredit");
	            $jq(this).find("span").html("&nbsp;&nbsp;&nbsp;");
	            $jq(this).find("span img").click(function () {
	                
	            });
	        });


	        $jq(".fblikessearchdropdownchoiceadd").click(function () {
	            var mainBox = $jq(this);

	            if (mainBox.attr("data-saved") == null || mainBox.attr("data-saved") == 0)
	            {
	                mainBox.attr("data-saved","1");
	                PeopleMedia.FacebookInterests.AddInterest(mainBox, mainBox.attr("data-interestid"));
	            }
	        });


	        $jq(".triggerfblikescontainer").click(function () {
	            $jq("#fblikescontainer").show();
	            $jq(".fblikessearchdropdown").hide();
	            $jq("#fblikessearchinput").val(PeopleMedia.FacebookInterests.DefaultSearchString);
	        });

	        $jq(".triggerrefresh").click(function () {
	            window.location = PeopleMedia.FacebookInterests.Actions.RefreshZoomInterests;
	        });

	        

	        $jq("#RunFacebookSearch").click(function () {
	            PeopleMedia.FacebookInterests.AttemptFacebookSearchTermLookup();
	        });

	        $jq("#fblikessearchinput").focus(function () {
	            if ($jq(this).val() == PeopleMedia.FacebookInterests.DefaultSearchString)
	            {
	                $jq(this).val("");
	            }
	        });

	        $jq("#fblikessearchinput").keyup(function () {
                PeopleMedia.FacebookInterests.AttemptFacebookSearchTermLookup();
	        });

	        $jq("#importfbbutton").click(function () {
	            PeopleMedia.FacebookInterests.AttemptLogin();
	        });

	    },
	    AddInterestFromSearch: function (mainBox, externalObjectId, interestName, totalLikes, categoryId) {

	        $jq("#fblikesimportcontainer").show();
	        $jq("#fblikesimportcontainerwait").hide();
	        $jq("#fblikesimportcontainercomplete").show();

	        mainBox.find("span").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Saving...");

	        var saveData = {};
	        saveData.Reviewed = false;
	        saveData.InterestId = 0;
	        saveData.ExternalObjectId = externalObjectId;
	        saveData.InterestName = interestName;
	        saveData.TotalLikes = totalLikes;
	        saveData.CategoryId = categoryId;

	        if (PeopleMedia.FacebookInterests.UserLikesAdded.length == 0) {
	            PeopleMedia.FacebookInterests.UserLikesAdded.push(saveData)
	            var myArray = JSON.stringify({ 'userLikes': PeopleMedia.FacebookInterests.UserLikesAdded });
	            $jq.ajax({
	                contentType: 'application/json; charset=utf-8',
	                dataType: 'json',
	                type: "POST",
	                url: PeopleMedia.FacebookInterests.Actions.AddInterestsUrl,
	                traditional: true,
	                data: myArray,
	                success: function (response) {
	                    var saveString = mainBox.find("span").html();
	                    saveString = saveString.replace("Saving...", "Saved!");
	                    mainBox.find("span").html(saveString);
	                    if (mainBox.hasClass("fblikechoice")) {
	                        mainBox.fadeOut("slow");
	                    }
	                    PeopleMedia.FacebookInterests.ShowAddSaveResults(response);
	                },
	                failure: function (response) {
	                    var saveString = mainBox.find("span").html();
	                    saveString = saveString.replace("Saving...", "Saved!");
	                    mainBox.find("span").html(saveString);
	                    if (mainBox.hasClass("fblikechoice")) {
	                        mainBox.fadeOut("slow");
	                    }
	                    PeopleMedia.FacebookInterests.ShowAddSaveResults(response);
	                }
	            });
	            PeopleMedia.FacebookInterests.UserLikesAdded = new Array();
	        }

	    },
	    AddInterest: function (mainBox, interestId) {

	        mainBox.find("span").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Saving...");

	        var saveData = {};
	        saveData.Reviewed = false;
	        saveData.InterestId = interestId;
	        saveData.ExternalObjectId = 0;
	        saveData.InterestName = 'Add';
	        saveData.TotalLikes = 0;
	        saveData.CategoryId = 0;

	        if (PeopleMedia.FacebookInterests.UserLikesAdded.length == 0) {
	            PeopleMedia.FacebookInterests.UserLikesAdded.push(saveData)
	            var myArray = JSON.stringify({ 'userLikes': PeopleMedia.FacebookInterests.UserLikesAdded });
	            $jq.ajax({
	                contentType: 'application/json; charset=utf-8',
	                dataType: 'json',
	                type: "POST",
	                url: PeopleMedia.FacebookInterests.Actions.AddInterestsUrl,
	                traditional: true,
	                data: myArray,
	                success: function (response) {
	                    var saveString = mainBox.find("span").html();
	                    saveString = saveString.replace("Saving...", "Saved!");
	                    mainBox.find("span").html(saveString);
	                    if (mainBox.hasClass("fblikechoice"))
	                    {
	                        mainBox.fadeOut("slow");
	                    }
	                    PeopleMedia.FacebookInterests.ShowAddSaveResults(response);
	                },
	                failure: function (response) {
	                    var saveString = mainBox.find("span").html();
	                    saveString = saveString.replace("Saving...", "Saved!");
	                    mainBox.find("span").html(saveString);
	                    if (mainBox.hasClass("fblikechoice")) {
	                        mainBox.fadeOut("slow");
	                    }
	                    PeopleMedia.FacebookInterests.ShowAddSaveResults(response);
	                }
	            });
	            PeopleMedia.FacebookInterests.UserLikesAdded = new Array();
	        }
	        
	    },
	    DeleteInterest: function(interestId){


	        var saveData = {};
	        saveData.Reviewed = false;
	        saveData.InterestId = interestId;
	        saveData.ExternalObjectId = 0;
	        saveData.InterestName = 'Delete';
	        saveData.TotalLikes = 0;
	        saveData.CategoryId = 0;

	        if (PeopleMedia.FacebookInterests.UserLikesDeleted.length == 0)
	        {
	            PeopleMedia.FacebookInterests.UserLikesDeleted.push(saveData)
	            var myArray = JSON.stringify({ 'userLikes': PeopleMedia.FacebookInterests.UserLikesDeleted });
	            $jq.ajax({
	                contentType: 'application/json; charset=utf-8',
	                dataType: 'json',
	                type: "POST",
	                url: PeopleMedia.FacebookInterests.Actions.DeleteInterestsUrl,
	                traditional: true,
	                data: myArray
	            });
	            PeopleMedia.FacebookInterests.UserLikesDeleted = new Array();
	        }

	    },
	    AttemptFacebookSearchTermLookup: function(){
	        var lookupString = $jq("#fblikessearchinput").val().trim();

	        if (PeopleMedia.FacebookInterests.CurrentSearchTermLookup.length == 0 && PeopleMedia.FacebookInterests.PreviousSearchTermLookup != lookupString)
	        {
	            $jq(".fblikessearchdropdown").show();

	            if (lookupString.length >= 3 && lookupString != PeopleMedia.FacebookInterests.DefaultSearchString) {

	                PeopleMedia.FacebookInterests.CurrentSearchTermLookup = lookupString;
	                PeopleMedia.FacebookInterests.PreviousSearchTermLookup = PeopleMedia.FacebookInterests.CurrentSearchTermLookup;

	                $jq(".fblikessearchdropdown").html("");
	                $jq.ajax({
	                    dataType: 'json',
	                    type: "GET",
	                    url: PeopleMedia.FacebookInterests.Actions.SearchInterestsUrl,
	                    data: { q: lookupString },
	                    success: function (response) {
	                        if (response.data != null) {
	                            for (var i = 0; i < response.data.length; i++) {
	                                var cat = "Unknown";

	                                switch (response.data[i].CategoryId) {
	                                    case 1: cat = "Movies"; break;
	                                    case 2: cat = "Music"; break;
	                                    case 3: cat = "Activities"; break;
	                                }

	                                $jq(".fblikessearchdropdown").append($jq('<div class="fblikessearchdropdownchoice fblikessearchdropdownchoiceaddsearch" data-interestname="' + response.data[i].InterestName + '" data-externalobjectid="' + response.data[i].ExternalObjectId + '" data-likes="' + response.data[i].TotalLikes + '" data-category="' + response.data[i].CategoryId + '">'
                                            + '<p><span>'
                                                + response.data[i].InterestName
                                            + '</span><br />'
                                            + cat + ' - ' + PeopleMedia.FacebookInterests.FormatLikes(response.data[i].TotalLikes) + ' like this</p>'
                                        + '</div>')
                                    );
	                            }

	                            $jq(".fblikessearchdropdownchoiceaddsearch").click(function () {
	                                var mainBox = $jq(this);
	                                if (mainBox.attr("data-saved") == null || mainBox.attr("data-saved") == 0) {
	                                    mainBox.attr("data-saved", "1");
	                                    PeopleMedia.FacebookInterests.AddInterestFromSearch(mainBox, mainBox.attr("data-externalobjectid"), mainBox.attr("data-interestname"), mainBox.attr("data-likes"), mainBox.attr("data-category"));
	                                }
	                            });

                                // clear search term
	                            PeopleMedia.FacebookInterests.CurrentSearchTermLookup = "";
	                        }
	                    }
	                });
	            }
	            else
	            {
	                $jq(".fblikessearchdropdown").hide();
	            }

	           
	        }

	    },
	    AttemptLogin: function () {

	        if (!PeopleMedia.FacebookInterests.FacebookInitRan) {
	            PeopleMedia.FacebookInterests.FacebookInitRan = true;

	            FB.init({
	                appId: PeopleMedia.FacebookInterests.AppID,
	                status: true, // check login status
	                cookie: true, // enable cookies 
	                xfbml: true, // parse XFBML
	                oauth: true
	            });

	            FB.Event.subscribe('auth.authResponseChange', function (response) {
	                if (response.status != "connected") {
	                    window.location.reload();
	                }
	                else {
	                    //$jq("#login").html('<a href="#" onclick="FB.logout();">Logout</a><br/>');
	                }
	            });

	            FB.getLoginStatus(function (response) {
	                if (response.status == "connected") {
	                    //$jq("#login").html('<a href="#" onclick="FB.logout();">Logout</a><br/>');
	                }
	            });

	            FB.login(PeopleMedia.FacebookInterests.LoginHandler, { scope: "user_interests, user_likes, user_photos" });
	        }
	        else
	        {
	            FB.login(PeopleMedia.FacebookInterests.LoginHandler, { scope: "user_interests, user_likes, user_photos" });
	        }
		   
	   },
	   LoginHandler: function(response) {
		    if (response.authResponse) {
		        PeopleMedia.FacebookInterests.CallFacebookAPIForImport();
		    }
		},	    
	    Output: function(message){
	        $jq("#LikesDisplayOutput").append(message + "<br />");
	    },
	    OutputHelper: function(response){
	    	PeopleMedia.FacebookInterests.Output("<hr />")
	    	for (x in response)
				{
					if (typeof(response[x]) === 'object' )
					{
						PeopleMedia.FacebookInterests.Output(x + "= {");
			      		for (y in response[x])
		      			{
		      				if (typeof(response[x][y]) === 'object' )
							{
								PeopleMedia.FacebookInterests.Output("&nbsp;&nbsp;" + y + " = {");
								for (z in response[x][y])
								{
									PeopleMedia.FacebookInterests.Output("&nbsp;&nbsp;&nbsp;&nbsp;" + z + " = " + response[x][y][z]);
								}
								PeopleMedia.FacebookInterests.Output("&nbsp;&nbsp;}");
							}
							else
							{
			      				PeopleMedia.FacebookInterests.Output(y + "=" + response[x][y]);							
							}
		      			}
		      			PeopleMedia.FacebookInterests.Output("}");
					}
					else
					{
						PeopleMedia.FacebookInterests.Output(x + "=" + response[x]);
					}
				}
	    }
	};
